package com.ruoyi.wb.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.wb.domain.WbMaintainCompanyUser;
import com.ruoyi.wb.dto.WbMaintainCompanyUserAddDto;
import com.ruoyi.wb.dto.WbMaintainCompanyUserPutDto;
import com.ruoyi.wb.dto.WbRoleDto;
import com.ruoyi.wb.enmus.PlanExecuteStatusEnums;
import com.ruoyi.wb.enmus.RoleNameEnums;
import com.ruoyi.wb.mapper.WbMaintainCompanyUserMapper;
import com.ruoyi.wb.mapper.WbPlanMapper;
import com.ruoyi.wb.service.IWbMaintainCompanyUserService;
import com.ruoyi.wb.vo.WbMaintainCompanyUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 维保公司 用户 关联Service业务层处理
 *
 * @author ruoyi
 * @date 2024-10-28
 */
@Service
public class WbMaintainCompanyUserServiceImpl implements IWbMaintainCompanyUserService {
    @Autowired
    private WbMaintainCompanyUserMapper wbMaintainCompanyUserMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private IWbMaintainCompanyUserService wbMaintainCompanyUserService;

    @Autowired
    private WbPlanMapper wbPlanMapper;

    @Autowired
    private RedisCache redisCache;

    /**
     * 查询维保公司 用户 关联
     *
     * @param id 维保公司 用户 关联主键
     * @return 维保公司 用户 关联
     */
    @Override
    public WbMaintainCompanyUserVo selectWbMaintainCompanyUserById(Long id) {
        return wbMaintainCompanyUserMapper.selectWbMaintainCompanyUserByUserId(id);
    }

    /**
     * 查询维保公司 用户 关联列表
     *
     * @param wbMaintainCompanyUser 维保公司 用户 关联
     * @return 维保公司 用户 关联
     */
    @Override
    public List<WbMaintainCompanyUserVo> selectWbMaintainCompanyUserList(WbMaintainCompanyUser wbMaintainCompanyUser) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //判断是否已经绑定了维保公司 如果绑定了就说明是管理人员只能查询自己的
        WbMaintainCompanyUser wbMaintainCompanyUser1 = new WbMaintainCompanyUser();
        wbMaintainCompanyUser1.setUserId(loginUser.getUserId());
        List<WbMaintainCompanyUser> wbMaintainCompanyUsers = wbMaintainCompanyUserMapper.selectWbMaintainCompanyUserList(wbMaintainCompanyUser1);
        if (!CollectionUtils.isEmpty(wbMaintainCompanyUsers)) {
            wbMaintainCompanyUser.setMaintainCompanyId(wbMaintainCompanyUsers.get(0).getMaintainCompanyId());
            //-----------------清空已经离职的用户-----------------
            //先查询本维保公司已经离职的用户
            List<Long> userIds=  wbMaintainCompanyUserService.selectDimissionUser(wbMaintainCompanyUsers.get(0).getMaintainCompanyId());
            //修改离职的用户还未完成的计划用户id为空
            if (!CollectionUtils.isEmpty(userIds)){
                wbPlanMapper.updateFireFightingIdByUserId(userIds,wbMaintainCompanyUsers.get(0).getMaintainCompanyId(), PlanExecuteStatusEnums.COMPLETED.getStatus().toString());
                wbPlanMapper.updateEngineerIdByUserId(userIds,wbMaintainCompanyUsers.get(0).getMaintainCompanyId(), PlanExecuteStatusEnums.COMPLETED.getStatus().toString());
                wbPlanMapper.updateOperaterIdUserId(userIds,wbMaintainCompanyUsers.get(0).getMaintainCompanyId(), PlanExecuteStatusEnums.COMPLETED.getStatus().toString());
            }
            //-----------------清空已经离职的用户-----------------

        }
        //查询出自己维保公司的关联信息
        PageUtils.startPage();
        return wbMaintainCompanyUserMapper.selectWbMaintainCompanyUserListByMaintainCompanyId(wbMaintainCompanyUser);
    }


    /**
     * 新增维保公司 用户 关联
     *
     * @param wbMaintainCompanyUserAddDto 维保公司用户关联入参
     * @return 结果
     */
    @Override
    @Transactional
    public int insertWbMaintainCompanyUser(WbMaintainCompanyUserAddDto wbMaintainCompanyUserAddDto) {
        //校验
        if (ObjectUtils.isEmpty(wbMaintainCompanyUserAddDto) || CollectionUtils.isEmpty(wbMaintainCompanyUserAddDto.getWbRoles())) {
            throw new RuntimeException("必须选择角色");
        }
        if (StringUtils.isNotEmpty(wbMaintainCompanyUserAddDto.getPassword())&&(wbMaintainCompanyUserAddDto.getPassword().length()<5 ||wbMaintainCompanyUserAddDto.getPassword().length()>20)){
            throw new RuntimeException("密码长度必须大于5位小于20位");
        }

        LoginUser loginUser = SecurityUtils.getLoginUser();
        //创建账号
        SysUser sysUser = new SysUser();
        sysUser.setPhonenumber(wbMaintainCompanyUserAddDto.getPhonenumber());
        sysUser.setUserName(wbMaintainCompanyUserAddDto.getUserName());
        sysUser.setNickName(wbMaintainCompanyUserAddDto.getNickName());
        sysUser.setSex(wbMaintainCompanyUserAddDto.getSex());
        sysUser.setPassword(SecurityUtils.encryptPassword(ObjectUtils.isEmpty(wbMaintainCompanyUserAddDto.getPassword()) ? WbMaintainCompanyUserAddDto.defaultPassword : wbMaintainCompanyUserAddDto.getPassword()));
        sysUser.setSignature(wbMaintainCompanyUserAddDto.getSignature());
        sysUser.setPersonalSeal(wbMaintainCompanyUserAddDto.getPersonalSeal());
        if (StringUtils.isEmpty(sysUser.getPhonenumber())) {
            throw new RuntimeException("手机号必填");
        }
        if (StringUtils.isEmpty(sysUser.getUserName())) {
            throw new RuntimeException("用户名必填");
        }

        //校验手机号
//        SysUser sysUser1 = sysUserMapper.checkPhoneUnique(sysUser.getPhonenumber());
//        if (!ObjectUtils.isEmpty(sysUser1)&&!sysUser1.getUserId().equals(wbMaintainCompanyUserAddDto.getUserId())) {
//            throw new RuntimeException("当前手机号已经存在");
//        }
        //校验用户名
        SysUser sysUser2 = sysUserMapper.checkUserNameUnique(sysUser.getUserName());
        if (!ObjectUtils.isEmpty(sysUser2)){//&&!sysUser2.getUserId().equals(wbMaintainCompanyUserAddDto.getUserId())
            throw new RuntimeException("当前账号已存在");
        }


        //为空创建账号  不为空 修改
      //  if (ObjectUtils.isEmpty(wbMaintainCompanyUserAddDto.getUserId())){
            int i = sysUserMapper.insertUser(sysUser);
            if (i == 0) {
                throw new RuntimeException("创建账号失败");
            }
//        }else{
//            sysUser.setUserId(wbMaintainCompanyUserAddDto.getUserId());
//            int i = sysUserMapper.updateUser(sysUser);
//            if (i == 0) {
//                throw new RuntimeException("修改失败");
//            }
//        }


        ArrayList<SysUserRole> sysUserRoles = new ArrayList<>();


        List<WbMaintainCompanyUser> wbMaintainCompanyUsers = new ArrayList<>();



        for (WbRoleDto role : wbMaintainCompanyUserAddDto.getWbRoles()) {
            //填充角色信息
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(sysUser.getUserId());
            sysUserRole.setRoleId(role.getRoleId());
            sysUserRoles.add(sysUserRole);
            //填充维保公司  用户关系表 信息
            WbMaintainCompanyUser wbMaintainCompanyUser = BeanUtil.copyProperties(wbMaintainCompanyUserAddDto, WbMaintainCompanyUser.class);
            wbMaintainCompanyUser.setUserId(sysUser.getUserId());
            wbMaintainCompanyUser.setRoleId(role.getRoleId());
            wbMaintainCompanyUser.setRoleName(role.getRoleName());
            wbMaintainCompanyUser.setCreateUserId(loginUser.getUserId());
            wbMaintainCompanyUser.setCreateUser(loginUser.getUsername());
            wbMaintainCompanyUser.setUpdateUser(loginUser.getUsername());
            wbMaintainCompanyUser.setCreateTime(DateUtils.getNowDate());
            wbMaintainCompanyUser.setUpdateTime(DateUtils.getNowDate());
            wbMaintainCompanyUsers.add(wbMaintainCompanyUser);
        }
        //插入用户角色关系表
        int k = sysUserRoleMapper.batchUserRole(sysUserRoles);
        if (k!=sysUserRoles.size()){
            throw new RuntimeException("创建角色失败");
        }


        return wbMaintainCompanyUserMapper.insertWbMaintainCompanyUsers(wbMaintainCompanyUsers);
    }

    /**
     * 修改维保公司 用户 关联
     *
     * @param wbMaintainCompanyUserPutDto 修改 维保公司用户关联入参
     * @return 结果
     */
    @Override
    @Transactional
    public int updateWbMaintainCompanyUser(WbMaintainCompanyUserPutDto wbMaintainCompanyUserPutDto) {

        if (ObjectUtils.isEmpty(wbMaintainCompanyUserPutDto.getUserId())){
            throw new RuntimeException("用户编号为空");
        }
        if (ObjectUtils.isEmpty(wbMaintainCompanyUserPutDto.getMaintainCompanyId())){
            throw new RuntimeException("维保公司编号为空");
        }

//        if (CollectionUtils.isEmpty(wbMaintainCompanyUserPutDto.getWbRoles())){
//            throw new RuntimeException("至少选择一个角色");
//        }


        LoginUser loginUser = SecurityUtils.getLoginUser();

        //修改传入的 用户 角色信息
        List<WbRoleDto> wbRoles = wbMaintainCompanyUserPutDto.getWbRoles();
        //新增角色
         if (!CollectionUtils.isEmpty(wbRoles)){
             //删除 角色
             wbMaintainCompanyUserMapper.deleteByUserIdAndMaintainCompanyId(wbMaintainCompanyUserPutDto.getUserId(), wbMaintainCompanyUserPutDto.getMaintainCompanyId());
             sysUserRoleMapper.deleteUserRoleByUserId(wbMaintainCompanyUserPutDto.getUserId());
             List<WbMaintainCompanyUser> wbMaintainCompanyUsers = new ArrayList<>();
             List<SysUserRole> sysUserRoles = new ArrayList<>();
             RoleNameEnums[] values = RoleNameEnums.values();
             Map<Integer, String> map = Arrays.stream(values).collect(Collectors.toMap(RoleNameEnums::getType, RoleNameEnums::getDescribe));

             wbRoles.forEach(item->{
                 WbMaintainCompanyUser wbMaintainCompanyUser = new WbMaintainCompanyUser();
                 wbMaintainCompanyUser.setRoleId(item.getRoleId());
                 wbMaintainCompanyUser.setRoleName(map.get(Integer.parseInt(item.getRoleId().toString())));
                 wbMaintainCompanyUser.setUserId(wbMaintainCompanyUserPutDto.getUserId());
                 wbMaintainCompanyUser.setMaintainCompanyId(wbMaintainCompanyUserPutDto.getMaintainCompanyId());
                 wbMaintainCompanyUser.setCreateUser(loginUser.getUsername());
                 wbMaintainCompanyUser.setCreateTime(DateUtils.getNowDate());
                 wbMaintainCompanyUser.setUpdateUser(loginUser.getUsername());
                 wbMaintainCompanyUser.setUpdateTime(DateUtils.getNowDate());
                 wbMaintainCompanyUser.setCreateBy(loginUser.getUserId().toString());
                 wbMaintainCompanyUser.setUpdateBy(loginUser.getUserId().toString());
                 wbMaintainCompanyUsers.add(wbMaintainCompanyUser);

                 SysUserRole sysUserRole = new SysUserRole();
                 sysUserRole.setUserId(wbMaintainCompanyUserPutDto.getUserId());
                 sysUserRole.setRoleId(item.getRoleId());
                 sysUserRoles.add(sysUserRole);
             });
             if (!CollectionUtils.isEmpty(wbMaintainCompanyUsers)){
                 wbMaintainCompanyUserMapper.insertWbMaintainCompanyUsers(wbMaintainCompanyUsers);
             }


             if (!CollectionUtils.isEmpty(sysUserRoles)){
                 sysUserRoleMapper.batchUserRole(sysUserRoles);
             }



         }
        SysUser sysUser = BeanUtil.copyProperties(wbMaintainCompanyUserPutDto, SysUser.class);
         if (StringUtils.isNotEmpty(wbMaintainCompanyUserPutDto.getUserName())){
             SysUser itemSysUser = sysUserMapper.selectUserByUserName(wbMaintainCompanyUserPutDto.getUserName());
             if (!ObjectUtils.isEmpty(itemSysUser)&&!itemSysUser.getUserId().equals(wbMaintainCompanyUserPutDto.getUserId())){
                 throw  new RuntimeException("账号已存在");
             }

             if (StringUtils.isNotEmpty(wbMaintainCompanyUserPutDto.getPassword())){
                 int length = wbMaintainCompanyUserPutDto.getPassword().length();
                 if (length<5||length>20){
                     throw new RuntimeException("密码长度不得小于5位或大于20位");
                 }
                 sysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPassword()));
             }
         }
        int i = sysUserMapper.updateUser(sysUser);
        if ((StringUtils.isNotEmpty(wbMaintainCompanyUserPutDto.getSex())
                ||StringUtils.isNotEmpty(wbMaintainCompanyUserPutDto.getNickName())
                ||StringUtils.isNotEmpty(wbMaintainCompanyUserPutDto.getUserName())
                ||StringUtils.isNotEmpty(wbMaintainCompanyUserPutDto.getPassword())
        )&&i==0){
            throw new RuntimeException("修改用户信息失败");
        }
        //----------------------更新redis缓存信息------------------------
        SysUser itemUser = sysUserMapper.selectUserById(wbMaintainCompanyUserPutDto.getUserId());
        if (StringUtils.isNotEmpty(itemUser.getToken())&&redisCache.hasKey(itemUser.getToken())){
            LoginUser itemLoginUser = redisCache.getCacheObject(itemUser.getToken());
            itemLoginUser.setUser(itemUser);
            redisCache.refreshToken(itemUser.getToken(),itemLoginUser);
        }
        return 1;
    }

    /**
     * 批量删除维保公司 用户 关联
     * @param userIds 需要删除的维保公司 用户 关联主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteWbMaintainCompanyUserByIds(Long[] userIds) {
        List<WbMaintainCompanyUser> wbMaintainCompanyUserList = wbMaintainCompanyUserMapper.selectWbMaintainCompanyUserListByUserIds(userIds);
        if (!CollectionUtils.isEmpty(wbMaintainCompanyUserList)) {
            Long[] ids = wbMaintainCompanyUserList.stream().map(WbMaintainCompanyUser::getId).collect(Collectors.toSet()).toArray(Long[]::new);
            int i = wbMaintainCompanyUserMapper.deleteWbMaintainCompanyUserByIds(ids);
            if (i != wbMaintainCompanyUserList.size()) {
                throw new RuntimeException("删除维保公司用户关系失败");
            }
        }
        //删除的时候同时删除账号
        int j = sysUserMapper.deleteUserByIdsTrue(userIds);

        int n = sysUserRoleMapper.deleteUserRole(userIds);

        return j;
    }

    /**
     * 删除维保公司 用户 关联信息
     *
     * @param id 维保公司 用户 关联主键
     * @return 结果
     */
    @Override
    public int deleteWbMaintainCompanyUserById(Long id) {
        return wbMaintainCompanyUserMapper.deleteWbMaintainCompanyUserById(id);
    }
    /**
     * 修改员工为离职
     * @return
     */
    @Override
    public int dimission(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setStatus(UserStatus.DISABLE.getCode());
        return  sysUserMapper.updateUser(sysUser);
    }

    //查询离职的员工
    @Override
    public List<Long> selectDimissionUser(Long maintainCompanyId) {
       return wbMaintainCompanyUserMapper.maintainCompanyId(maintainCompanyId,UserStatus.DISABLE.getCode(),UserStatus.DELETED.getCode());

    }

    /**
     * 查询维保师傅
     * @return
     */
    @Override
    public List<WbMaintainCompanyUserVo> listWbMaster() {


        RoleNameEnums[] values = RoleNameEnums.values();
        List<String> roleIds = new ArrayList<>();
        for (RoleNameEnums value : values) {
            if (value.isIfWbRole()){
                roleIds.add(value.getType().toString());
            }
        }
         if (CollectionUtils.isEmpty(roleIds)){
             return new ArrayList<WbMaintainCompanyUserVo>();
         }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        WbMaintainCompanyUser wbMaintainCompanyUser = new WbMaintainCompanyUser();
        wbMaintainCompanyUser.setUserId(loginUser.getUserId());

        List<WbMaintainCompanyUser> wbMaintainCompanyUsers = wbMaintainCompanyUserMapper.selectWbMaintainCompanyUserList(wbMaintainCompanyUser);

        if (!CollectionUtils.isEmpty(wbMaintainCompanyUsers)){
            return  wbMaintainCompanyUserMapper.listWbMaster(roleIds,wbMaintainCompanyUsers.get(0).getMaintainCompanyId());
        }
        return  wbMaintainCompanyUserMapper.listWbMaster(roleIds,null);
    }


}
